// Implement your part 1 solution here
// gcc vfork.c -o vfork
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

char colors[64][64 * 3]; // 64 rows of 64 pixels with 3 color values each (RGB)

void paint(int workID)
{
    printf("Artist %d is painting\n", workID);

    for (int i = 0; i < 64 * 3; i++)
    {
        colors[workID][i] = workID;
    }
}

void outputPPM()
{
    FILE *fp;
    fp = fopen("vfork.ppm", "w+");
    fputs("P3\n", fp);
    fputs("64 64\n", fp);
    fputs("255\n", fp);
    for (int i = 0; i < 64; i++)
    {
        for (int j = 0; j < 64 * 3; j++)
        {
            fprintf(fp, "%d", colors[i][j]);
            fputs(" ", fp);
        }
        fputs("\n", fp);
    }
    fclose(fp);
}

int main(int argc, char **argv)
{
    int numberOfArtists = 64;
    pid_t pid;
    int *integers = malloc(sizeof(int) * 8000);

    // main loop where we fork new threads
    for (int i = 0; i < numberOfArtists; i++)
    {
        // perform a fork
        pid = vfork();
        // make only the child do some work and then terminate
        if (pid == 0)
        {
            paint(i);
            exit(0);
        }
        printf("Child created: %d\n", pid);
    }

    // wait for all children to finish
    pid_t wpid;
    int status = 0;
    while ((wpid = wait(&status)) > 0)
        ;

    printf("parent is exiting(last artist out!)\n");

    printf("Masterpiece(vfork.ppm) is being assembled\n");
    outputPPM(); // output the ppm file

    free(integers); // free the memory

    return 0;
}
